<template>
  <!-- page: Login -->
  <div class = "login-page mx-auto p-3 w-330">
    <h5 class = "my-4 text-center">登录到知乎</h5>
    <validate-form v-on:form-submit="onFormSubmit">
      <div class = "mb-3">
        <label class = "form-label">Email:</label>
        <validate-input
          type = "text"
          placeholder = "请输入邮箱"
          v-bind:rules="emailRules"
          ref="inputRef"
          v-model="emailVal"
        ></validate-input>
      </div>
      <div class = "mb-3">
        <label class = "form-label">Password:</label>
        <validate-input
          type = "password"
          placeholder = "请输入密码"
          v-bind:rules="passwordRules"
          v-model="passwordVal"
        ></validate-input>
      </div>
      <template #submit>
        <button type = "submit" class = "btn btn-primary btn-block btn-large">登录</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang = "ts">
import { defineComponent, ref } from 'vue'
// 导入钩子函数 vuex
import { useStore } from 'vuex'
// 导入钩子函数 vue-router
import { useRouter } from 'vue-router'
// 导入组件
import ValidateInput, { RulesProp } from '@/components/ValidateInput.vue'
import ValidateForm from '@/components/ValidateForm.vue'
// 导入 消息提示
import createMessage from '@/assets/js/createMessage'

// 对setup函数进行封装，返回options的对象
export default defineComponent({
  // 页面名称
  name: 'Login',

  // 注册组件
  components: {
    ValidateInput, ValidateForm
  },

  // 组合式api入口
  setup () {
    const router = useRouter()
    const store = useStore()
    // 默认input - email显示内容
    const emailVal = ref('')
    // 默认input - password显示内容
    const passwordVal = ref('')
    // 邮箱验证规则
    const emailRules: RulesProp = [
      { type: 'required', message: '邮箱不能为空' },
      { type: 'email', message: '请输入正确的邮箱' }
    ]
    // 密码验证规则
    const passwordRules: RulesProp = [
      { type: 'required', message: '密码不能为空' }
    ]
    // 登录账户
    const onFormSubmit = (result: boolean) => {
      // console.log('result', result)
      if (result) {
        // 获取登录账户的数据
        const payload = {
          email: emailVal.value,
          password: passwordVal.value
        }
        // 账户登录成功 跳转回首页
        store.dispatch('loginAndFetch', payload).then(data => {
          createMessage('登录成功, 2秒后跳转回首页', 'success')
          setTimeout(() => {
            router.push('/')
          }, 2000)
        }).catch(e => {
          console.log(e)
        })
      }
    }
    return {
      emailRules,
      emailVal,
      passwordRules,
      passwordVal,
      onFormSubmit
    }
  }
})
</script>

<style lang="css" scoped>
</style>
